package com.zgy.myshellcommand.handler.impl;


import cn.hutool.core.io.FileUtil;
import cn.hutool.crypto.SecureUtil;
import com.zgy.myshellcommand.handler.CryptHandler;
import org.springframework.shell.command.CommandContext;
import org.springframework.stereotype.Component;

import java.nio.file.Paths;

import static com.zgy.myshellcommand.enums.FileCoyptOptionsEnum.*;

@Component
public class CryptHandlerImpl implements CryptHandler {

    @Override
    public void cryptHelp() {
        System.out.println("包含两个子命令:");
        System.out.printf("[%s|%s]:%s%n\t使用%s %s --help查看帮助%n",Encrypt.getLongName(),Encrypt.getShortName(),Encrypt.getDescription(),Command.getLongName(),Encrypt.getShortName());
        System.out.printf("[%s|%s]:%s%n\t使用%s %s --help查看帮助%n",Decrypt.getLongName(),Decrypt.getShortName(),Decrypt.getDescription(),Command.getLongName(),Decrypt.getShortName());
        System.out.printf("[%s|%s]:%s%n\t使用%s %s --help查看帮助%n", ReadEncrypt.getLongName(), ReadEncrypt.getShortName(), ReadEncrypt.getDescription(),Command.getLongName(), ReadEncrypt.getShortName());

    }

    @Override
    public String encrypt(CommandContext ctx) {
        ;
        if (ctx.hasMappedOption(Str.getLongName())){
            String encryptHex = SecureUtil.aes(getKey(ctx)).encryptHex((String) ctx.getOptionValue(Str.getLongName()));
            return encryptHex;
        }
        if (ctx.hasMappedOption(File.getLongName())){
            String optionValue = ctx.getOptionValue(File.getLongName());
            String encFile = Paths.get(optionValue).toAbsolutePath().toString() + ".enc";
            SecureUtil.aes(getKey(ctx)).encrypt(FileUtil.getInputStream(optionValue),
                    FileUtil.getOutputStream(encFile),true);
            return encFile;
        }
        return "执行失败";

    }

    private static byte[] getKey(CommandContext ctx) {
        return SecureUtil.sha256().digest(((String)ctx.getOptionValue(Passwd.getLongName())).getBytes());
    }

    @Override
    public String decrypt(CommandContext ctx) {
        if (ctx.hasMappedOption(Str.getLongName())){
            String decryptHex = SecureUtil.aes(getKey(ctx)).decryptStr((String) ctx.getOptionValue(Str.getLongName()));
            return decryptHex;
        }
        if (ctx.hasMappedOption(File.getLongName())){
            String optionValue = ctx.getOptionValue(File.getLongName());
            String decFile = Paths.get(optionValue).toAbsolutePath().toString() + ".dec";
            SecureUtil.aes(getKey(ctx)).decrypt(FileUtil.getInputStream(optionValue),
                    FileUtil.getOutputStream(decFile),true);
            return decFile;
        }
        return "执行失败";

    }

    @Override
    public String readPasswd(CommandContext ctx) {
        String passwdPath = ctx.getOptionValue(File.getLongName());
        return SecureUtil.aes(getKey(ctx)).decryptStr(FileUtil.getInputStream(passwdPath));
    }

}
